import { getAddressList, deleteAddress, setDefaultAddress, addAddress, editAddress } from '../services/address'
import { message } from 'antd'
export default {

  namespace: 'address',

  state: {
    addressList: []
  },

  subscriptions: {
    setup({ dispatch, history }) {
    },
  },

  effects: {
    *fetch({ payload }, { call, put }) {
      const res = yield call(getAddressList, payload);
      if (res.data.code == 0) {
        yield put({ type: 'save', payload: res.data.data });
      }
    },
    *delete({ payload }, { call, put }) {
      const res = yield call(deleteAddress, payload);
      if (res.data.code == 0 && res.data.data) {
        message.destroy()
        message.success('操作成功')
        const refreshAddress = yield call(getAddressList);
        yield put({ type: 'save', payload: refreshAddress.data.data });
      }
    },
    *defaultAddress({ payload }, { call, put }) {
      const res = yield call(setDefaultAddress, payload);
      if (res.data.code == 0 && res.data.data) {
        message.destroy()
        message.success('操作成功')
        const refreshAddress = yield call(getAddressList);
        yield put({ type: 'save', payload: refreshAddress.data.data });
      }
    },
    *add({ payload }, { call, put }) {
      const res = yield call(addAddress, payload);
      if (res.data.code == 0 && res.data.data) {
        message.destroy()
        message.success('操作成功')
        const refreshAddress = yield call(getAddressList);
        yield put({ type: 'save', payload: refreshAddress.data.data });
      }
    },
    *edit({ payload }, { call, put }) {
      const res = yield call(editAddress, payload);
      if (res.data.code == 0 && res.data.data) {
        message.destroy()
        message.success('操作成功')
        const refreshAddress = yield call(getAddressList);
        yield put({ type: 'save', payload: refreshAddress.data.data });
      }
    },
  },

  reducers: {
    save(state, action) {
      return { ...state, addressList: action.payload };
    }
  },

};
